import Taro from '@tarojs/taro';

import { baseURL } from './apiConfig';


//网络请求拦截器
const interceptor = function (chain) {
  const requestParams = chain.requestParams
  const { url } = requestParams
  let token = Taro.getStorageSync('token')//拿到本地缓存中存的token

  if (!url.includes('/login')) {
    requestParams.header = {
      ...requestParams.header,
      Authorization: 'Bearer ' + token //将token添加到头部
    }
  }
  return chain.proceed(requestParams).then(res => { return res })
}

Taro.addInterceptor(interceptor);


const request = (options): Promise<any> => {

  const { url, method, data, header } = options;
  const fullUrl = `${baseURL}${url}`;

  return new Promise((resolve, reject) => {
    Taro.request({
      url: fullUrl,
      method,
      data,
      header: {
        'Content-Type': 'application/json',
        ...header,
      },

    }).then((res) => {
      if (res.statusCode == 200) {

        if (url.includes('/login') && res.header['authorization']) {
          console.log(res.header['authorization'], '登录成功，保存token');

          Taro.setStorageSync('token', res.header['authorization']);
        }
        resolve(res.data);
      } else if (res.statusCode == 403) {
        Taro.showModal({
          title: '提示',
          content: '获取用户信息失败，请重新登录',
          success: function (res) {
            if (res.confirm) {
              Taro.navigateTo({
                url: '/pages/profile/index',
              })
            }
          }
        })
        reject(res);
      } else {
        Taro.showToast({ title: '请求异常：' + res.statusCode, icon: 'none' });
        reject(res);
      }
    }).catch((err) => {
      Taro.showToast({ title: '网络异常', icon: 'error' });
      reject(err);
    })
  }
  )
}


export { request };